package com.um.jdy.common.system.service.impl;

import com.um.jdy.common.system.entity.vo.MenuNode;
import com.um.jdy.common.system.entity.vo.MenuTreeNode;
import com.um.jdy.common.system.service.MenuTreeService;
import com.um.springboot.starter.orm.entity.TreeNode;
import com.um.springboot.starter.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 邓南辉
 * 日期 2023/6/28
 * 版权所有 广州优匠科技有限公司
 */
@Service
public class MenuTreeServiceImpl implements MenuTreeService {

    /**
     * 复制集合
     * @param list
     * @return
     */
    @Override
    public List<MenuTreeNode> toTreeNodeList(List<MenuNode> list) {
        List<MenuTreeNode> array = new ArrayList<>();

        try {
            for (MenuNode entity : list) {
                MenuTreeNode node = MenuTreeNode.class.newInstance();
                /** 拷贝*/
                BeanUtils.copyProperties(entity, node);

                node.setId(entity.getSysMenuId());
                node.setSelected(entity.getSelected());
                node.setParentId(entity.getSysMenuParentId());
                node.setMenu(entity.getLinkUrl());
                array.add(node);
            }
        }catch (Exception ex){
            //log.error("",ex);
        }

        return array;
    }

    /**
     * 列表转成树集合
     * @param parentId
     * @param list
     * @return
     */
    @Override
    public MenuTreeNode listToTreeNode(String parentId, List<MenuTreeNode> list){
        List<TreeNode> nodes = new ArrayList<>();
        MenuTreeNode parentNode = null;

        for (MenuTreeNode node : list) {
            if (StringUtil.getTrim(node.getParentId()).equals(parentId)) {
                nodes.add(findChildren(node, list));
            }

            if(node.getId().equals(parentId)){
                parentNode = node;
            }
        }
        if(null != parentNode){
            parentNode.setNodes(nodes);
        }
        return parentNode;
    }

    protected MenuTreeNode findChildren(MenuTreeNode tree, List<MenuTreeNode> list) {
        for (MenuTreeNode node : list) {
            if (StringUtil.getTrim(node.getParentId()).equals(tree.getId())) {

                tree.getNodes().add(findChildren(node, list));
            }
        }
        return tree;
    }
}
